package main

import (
	"context"
	"fmt"
	"io"
	"net"

	"gitlab.com/go-course-project/go17/skills/grpc/service"
	"google.golang.org/grpc"
)

type HelloServiceServer struct {
	service.UnimplementedHelloServiceServer
}

func (HelloServiceServer) Hello(ctx context.Context, req *service.HelloRequest) (*service.HelloResponse, error) {
	return &service.HelloResponse{
		Message: "hello, " + req.MyName,
	}, nil
}

func (HelloServiceServer) Chat(stream grpc.BidiStreamingServer[service.ChatRequest, service.ChatResponse]) error {
	// 1. 获取用户的请求，然后处理, 处理完成后，通过stream 返回给客户端
	for {
		// 接收一个请求
		req, err := stream.Recv()
		if err != nil {
			// 如果遇到io.EOF表示客户端流被关闭
			if err == io.EOF {
				return nil
			}
			return err
		}

		// 2. 处理请求
		fmt.Println(req.Message)
		stream.Send(&service.ChatResponse{
			Id:        req.Id,
			IsSuccess: true,
		})
	}
}

func main() {
	// 1. 示例化一个grpc server对象
	server := grpc.NewServer()
	service.RegisterHelloServiceServer(server, &HelloServiceServer{})

	// 2. 启动grpc服务
	lis, err := net.Listen("tcp", ":1234")
	if err != nil {
		panic(err)
	}
	if err := server.Serve(lis); err != nil {
		panic(err)
	}
}
